import asyncio
from concurrent.futures import ThreadPoolExecutor
from letter.letter_processor import LetterProcessor


class LetterProcessorService:
    """来信件处理服务类"""

    def __init__(self, thread_pool: ThreadPoolExecutor):
        self.thread_pool = thread_pool
        self.letter_processor = LetterProcessor(thread_pool)

    async def process_letter_async(
        self,
        bh: str,
        case_content: str,
        txm: str,
    ):
        """
        异步处理来信件的主要函数

        Args:
            bh: 编号
            case_content: 信访件内容
            txm: 条形码

        Returns:
            处理结果字典
        """
        try:
            # 调用原有的处理器
            result = await self.letter_processor.process_letter_async(
                bh=bh, case_content=case_content, txm=txm
            )
            return result
        except Exception as e:
            # 记录错误并重新抛出
            await self.async_log_error(bh, f"处理失败: {str(e)}")
            raise

    async def async_log_error(self, bh: str, message: str):
        """异步记录错误日志"""
        await asyncio.get_event_loop().run_in_executor(
            self.thread_pool,
            lambda: print(f"Error for {bh}: {message}"),  # 简化错误记录
        )
